package controller

import (
	"etcd/e"
	"etcd/models"
	"etcd/utile"
	"github.com/gin-gonic/gin"
	"strings"
)

var adminModel models.Admin

type User struct {
	Name   string `json:"name"`
	Avatar string `json:"avatar"`
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	captchaId := c.PostForm("captcha_id")
	captcha := c.PostForm("captcha")
	//fmt.Printf("%s, %s, %s, %s", mobile, password, captchaId, captcha)
	res := utile.VerifyCaptcha(captchaId, captcha)
	if !res {
		Error(c,e.ERROR_VERIFY_CAPTCHA)
		return
	}

	//admin := adminModel.FindByUsername(mobile)

	//var admin entity.Admin
	//admin.Username = mobile
	//adminModel.FindOne(&admin)
	//if len(admin.Password) < 1 || admin.Password != utile.Md5(password) {
	//	c.JSON(http.StatusOK, utile.ReturnData(e.ERROR_LOGIN, e.GetMsg(e.ERROR_LOGIN)))
	//	return
	//}

	res = checkUserByEtcd(username,password)

	if !res {
		Error(c,e.ERROR_LOGIN)
		return
	}

	token, err := utile.CreatToken(1)
	if err != nil {
		Error(c,e.ERROR_CREATE_CAPTCHA)
		return
	}
	c.Header("Authorization", "Bearer "+token)
	//fmt.Println("token:" + token)

	//uid, err := utile.ParseToken(token)
	//fmt.Println(uid)
	Success(c,User{"admin", ""})
}

func checkUserByEtcd(username,password string) bool {
	etcd := utile.GetEtcd()
	edata,err := etcd.Get(username)
	if err != nil {
		return false
	}
	if !strings.EqualFold(edata.Val,utile.Md5(password)) {
		return false
	}
	return true
}